package logic

import (
	"context"
	"errors"
	"fmt"
	"gozero_test/common/cryptx"
	"gozero_test/common/errorx"
	"gozero_test/common/jwtx"
	"gozero_test/model"
	"time"

	"gozero_test/internal/svc"
	"gozero_test/internal/types"

	"github.com/tal-tech/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) LoginLogic {
	return LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req types.LoginRequest) (*types.LoginResponse, error) {
	// todo: add your logic here and delete this line
	res, err := l.svcCtx.UserModel.FindOneByMobile(req.Mobile)
	if err != nil {
		if err == model.ErrNotFound {
			return nil, errorx.NewCodeError(1001, "用户不存在")
		}
		return nil, errors.New(err.Error())
	}

	password := cryptx.PasswordEncrypt(l.svcCtx.Config.Salt, req.Password)
	fmt.Println(password)
	fmt.Println(res)
	if password != res.Password {
		return nil, errorx.NewCodeError(1002, "密码错误")
	}
	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire

	accessToken, err := jwtx.GetToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, res.Id)
	if err != nil {
		return nil, err
	}

	return &types.LoginResponse{
		AccessToken:  accessToken,
		AccessExpire: now + accessExpire,
	}, nil
}
